import pyodbc

class AccessDBManager:
    def __init__(self, db_path):
        self.db_path = db_path
        self.conn = None

    def connect(self):
        try:
            conn_str = r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=' + self.db_path
            self.conn = pyodbc.connect(conn_str)
            return True
        except Exception as e:
            print(f"数据库连接失败: {e}")
            return False

    def execute_query(self, query, params=None):
        if not self.conn:
            print("数据库未连接，请先调用 connect 方法。")
            return None
        try:
            cursor = self.conn.cursor()
            if params:
                cursor.execute(query, params)
            else:
                cursor.execute(query)
            if query.strip().lower().startswith('select'):
                result = cursor.fetchall()
                return result
            else:
                self.conn.commit()
                return cursor.rowcount
        except Exception as e:
            print(f"执行 SQL 语句失败: {e}")
            self.conn.rollback()
            return None

    def close(self):
        if self.conn:
            self.conn.close()
            self.conn = None